<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="index.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        canvas {
            margin: 50px auto 0;
            display: block;
            background: yellow;
        }
    </style>
</head>
<body>
<canvas id="canvas" width="400" height="400">
    此浏览器不支持canvas
</canvas>
</body>
</html>
<script>
    const ctx = document.getElementById('canvas')
    const gl = ctx.getContext('webgl')

    const VERTEX_SHADER_SORUCE = `
    attribute vec4 aPosition;
    attribute vec4 aTex;
    varying vec2 vTex;
    void main(){
      gl_Position = aPosition;
      vTex = vec2(aTex.x,aTex.y);
    }
  `;
    const FRAGEMNT_SHADER_SOURCE = `
    precision lowp float;
    uniform sampler2D uSampler;
    varying vec2 vTex;
    void main(){
      gl_FragColor = texture2D(uSampler,vTex);
    }
  `;
    // 封装后
    const program = initShader(gl, VERTEX_SHADER_SORUCE, FRAGEMNT_SHADER_SOURCE)
    const aPosition = gl.getAttribLocation(program, 'aPosition');
    const aTex = gl.getAttribLocation(program, 'aTex');
    const uSampler = gl.getUniformLocation(program, 'uSampler');
    // 顶点数据
    const points = new Float32Array([
        -0.5, 0.5,0.0,1.0,
        -0.5, -0.5,0.0,0.0,
        0.5, 0.5,1.0,1.0,
        0.5, -0.5,1.0,0.0,
    ])
    const buffer = gl.createBuffer();
    const BYTES = points.BYTES_PER_ELEMENT;

    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

    gl.bufferData(gl.ARRAY_BUFFER,points,gl.STATIC_DRAW);

    gl.vertexAttribPointer(aPosition,2,gl.FLOAT,false,BYTES*4,0);
    // 激活aPosition
    gl.enableVertexAttribArray(aPosition)
    gl.vertexAttribPointer(aTex,2,gl.FLOAT,false,BYTES*4,BYTES*2);
    // 激活aPosition
    gl.enableVertexAttribArray(aTex)

    const img = new Image();
    img.onload = function () {
        // 创建纹理对象
        const texture = gl.createTexture();
        // gl.deleteTexture(texture) 用来删除纹理对象
        // 翻转 图片 Y轴
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1)

        // 开启一个纹理单元
        gl.activeTexture(gl.TEXTURE0);

        // 绑定纹理对象
        gl.bindTexture(gl.TEXTURE_2D, texture);

        // 处理放大缩小的逻辑
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)

        // 横向 纵向 平铺的方式
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)

        // 配置纹理图像
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, img);

        gl.uniform1i(uSampler, 0);

        gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
    }
    img.src='../assets/content.png'
</script>
